package com.lgx.common.web.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * 短信工具
 * 
 * @author acer
 *
 */
public class SMSUtils {

	/**
	 * 短信接口地址
	 */
	public static final String SMS_URL = "http://kydx.gotoip1.com/smsapi/sms.php";
	
	/**
	 * 短信接口用户名标识
	 */
	public static final String SMS_USERNAME = "username";
	
	/**
	 * 短信接口用户名
	 */
	public static final String SMS_USERNAME_VALUE = "一卡淘";
	
	/**
	 * 短信接口密码标识
	 */
	public static final String SMS_PASSWORD = "password";
	
	/**
	 * 短信接口密码
	 */
	public static final String SMS_PASSWORD_VALUE = "123321";
	
	/**
	 * 短信后缀标识
	 */
	public static final String SMS_SIGN = "【乐共享】";
	
	protected static Logger log = Logger.getLogger(SMSUtils.class);
	
	/**
	 * 发送手机短信
	 * 
	 * @param mobile 手机号码，多个用逗号隔开
	 * @param content 短信内容
	 */
	public static void sendSMS(String mobile,String content){
		
		StringBuffer sb = new StringBuffer();
		sb.append(SMS_URL);
		sb.append("?"+SMS_USERNAME+"="+SMS_USERNAME_VALUE);
		sb.append("&"+SMS_PASSWORD+"="+SMS_PASSWORD_VALUE);
		sb.append("&mobile="+mobile);
		sb.append("&content="+content);
		
		try {
			// 创建url对象
			URL url = new URL(sb.toString());

			// 打开url连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			// 设置url请求方式 ‘get’ 或者 ‘post’
			connection.setRequestMethod("POST");

			// 发送
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

			// 返回发送结果
			String inputline = in.readLine();

			// 返回结果为‘success’ 发送成功
			if(inputline.contains("success")){
				log.info("[短信发送成功]："+inputline);
			}else{
				log.info("[短信发送失败]");
			}
			
			in.close();
			
			connection.disconnect();// 断开连接
		} catch (MalformedURLException e) {
			e.printStackTrace();
			log.info("[短信发送失败]");
		} catch (ProtocolException e) {
			e.printStackTrace();
			log.info("[短信发送失败]");
		} catch (IOException e) {
			e.printStackTrace();
			log.info("[短信发送失败]");
		}
	}
}
